package com.pn.service.impl;

import com.pn.dto.AssignAuthDto;
import com.pn.entity.Result;
import com.pn.mapper.RoleAuthMapper;
import com.pn.mapper.RoleMapper;
import com.pn.model.Role;
import com.pn.model.RoleAuth;
import com.pn.page.Page;
import com.pn.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collections;
import java.util.List;

/**
 * ClassName:RoleServiceImpl
 * Package:com.pn.service.impl
 * Description:
 *
 * @date:2024/12/29 19:51
 * @author:bailihua
 */
//2、指定缓存的名称（数据保存到redis中的键的前缀，一般值给类的全路径）
@CacheConfig(cacheNames = "com.pn.service.impl.RoleServiceImpl")
@Service
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleAuthMapper roleAuthMapper;
    /**
     * 查询所有角色
     * @return
     */
    //3、查询方法上标注指定缓存的键
    @Cacheable(key = "'all:role'")
    @Override
    public List<Role> queryAllRole() {
        return roleMapper.findAllRole();
    }

    /**
     * 根据用户Id查询用户已经被分配的角色
     * @param userId
     * @return
     */
    @Override
    public List<Role> queryUserRoleByUid(Integer userId) {
        return roleMapper.findUserRoleByUid(userId);
    }

    /**
     * 分页查询角色
     * @param page
     * @param role
     * @return
     */
    @Override
    public Page queryRolePage(Page page, Role role) {
        //查询角色行数
        Integer count = roleMapper.findRoleRowCount(role);

        //分页查询角色
        List<Role> roleList = roleMapper.findRolePage(page,role);

        //组装分页信息
        page.setTotalNum(count);
        page.setResultList(roleList);
        return page;
    }

    /**
     * 添加角色
     * @param role
     * @return
     */
    @CacheEvict(key = "'all:role'")
    @Override
    public Result saveRole(Role role) {

        //判断角色是否存在
        Role r = roleMapper.findRoleByNameOrCode(role.getRoleName(),role.getRoleCode());
        if(r != null){
            return Result.err(Result.CODE_ERR_BUSINESS,"角色已存在！");
        }
        //角色不存在，添加角色
        int i = roleMapper.insertRole(role);
        if(i>0){
            return  Result.ok("角色添加成功");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"角色添加失败");

    }

    /**
     * 启用或者禁用角色
     * @param role
     * @return
     */
    @CacheEvict(key = "'all:role'")
    @Override
    public Result setRoleState(Role role) {
        int i = roleMapper.setRoleStateByRid(role.getRoleId(),role.getRoleState());
        if(i>0){
            return Result.ok("角色启用或禁用成功!");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"角色启用或禁用失败！");
    }

    /**
     * 删除角色
     * @param roleId
     * @return
     */
    @CacheEvict(key = "'all:role'")
    @Override
    public Result deleteRoleById(Integer roleId) {
        int i = roleMapper.removeRoleById(roleId);
        if(i>0){
            //删除角色权限关系
            roleAuthMapper.removeRoleAuthByRid(roleId);
            //返回成功的响应结果对象
            return Result.ok("角色删除成功！");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"角色删除失败！");
    }

    /**
     * 查询角色分配的所有权限菜单
     * @param roleId
     * @return
     */
    @Override
    public List<Integer> queryRoleAuthIds(Integer roleId) {
        return roleAuthMapper.findAuthIdsByRid(roleId);
    }

    /**
     * 给角色分配权限
     * @param assignAuthDto
     */
    @Transactional//开启事务
    @Override
    public void saveRoleAuth(AssignAuthDto assignAuthDto) {
        //删除角色之前分配的所有权限
        roleAuthMapper.removeRoleAuthByRid(assignAuthDto.getRoleId());

        //添加角色权限关系
        List<Integer> authIdList = assignAuthDto.getAuthIds();
        for (Integer authId : authIdList) {
            RoleAuth roleAuth = new RoleAuth();
            roleAuth.setRoleId(assignAuthDto.getRoleId());
            roleAuth.setAuthId(authId);
            roleAuthMapper.insertRoleAuth(roleAuth);
        }
    }

    /**
     * 修改角色
     * @param role
     * @return
     */
    @CacheEvict(key = "'all:role'")
    @Override
    public Result setRoleByRid(Role role) {

        int i = roleMapper.setDescByRid(role);
        if(i>0){
            return Result.ok("角色修改成功!");
        }
        return Result.err(Result.CODE_ERR_BUSINESS,"角色修改失败！");
    }
}
